﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Text;
using System.Web.Caching;
using System.Diagnostics;
using System.Net;
using System.IO;
using DGSFramework;


namespace Framework
{
    public class Global : GlobalGZip
    {
        private string DummyCacheItemKey = "RemoveResizeUploadImage";
        private string DummyPageUrl = ConfigPaths.Domain_Url + "Default.aspx";

        private void HitPage()
        {
            WebClient client = new WebClient();
            client.DownloadData(DummyPageUrl);
        }

        public void CleanImageUploadTemp()
        {
            if (DateTime.Now.Hour >= 2 && DateTime.Now.Hour <= 3)
            {
                foreach (var file in Directory.GetFiles(System.Web.Hosting.HostingEnvironment.MapPath(ConfigPaths.Path_ImageUploadTemp_Folder_MapPath)))
                {
                    File.Delete(file);
                }
            }
        }

        private void ClearDBLog()
        {
            if (DateTime.Now.Hour >= 2 && DateTime.Now.Hour <= 3)
            {
                DGSFrameworkEntities entity = new DGSFrameworkEntities();
                DateTime timeTemp = DateTime.Now.AddMonths(-3);
                List<udv_Log> logs = entity.udv_Log.Where(ar => ar.ActionedDate.Value <= timeTemp).ToList();
                if (logs != null && logs.Count > 0)
                {
                    logs.ForEach(lg => entity.DeleteObject(lg));
                    entity.SaveChanges();
                }
            }
        }

        public void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
        {
            Debug.WriteLine("Cache item callback: " + DateTime.Now.ToString());

            HitPage();

            // Do the service works
            CleanImageUploadTemp();
            ClearDBLog();
        }

        private bool RegisterCacheEntry()
        {
            if (null != HttpContext.Current.Cache[DummyCacheItemKey])
                return false;

            HttpContext.Current.Cache.Add(DummyCacheItemKey, "ResizeUploadImage", null,
                DateTime.MaxValue, TimeSpan.FromMinutes(20),
                CacheItemPriority.Normal,
                new CacheItemRemovedCallback(CacheItemRemovedCallback));

            return true;
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            RegisterCacheEntry();

            Application["UserOnline"] = 0;
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            Application.Lock();
            Application["UserOnline"] = Convert.ToInt32(Application["UserOnline"].ToString()) + 1;
            Application.UnLock();

            //try
            //{
            //    System.IO.StreamReader sr = new System.IO.StreamReader(Request.PhysicalApplicationPath + "\\counter.txt");
            //    string str = sr.ReadLine();

            //    int total = int.Parse(str) + 1;
            //    Application["Total"] = total;
            //    sr.Dispose();
            //    sr.Close();

            //    System.IO.StreamWriter sw = new System.IO.StreamWriter(Request.PhysicalApplicationPath + "\\counter.txt");

            //    sw.Write(total.ToString());
            //    sw.Flush();
            //    sw.Dispose();
            //    sw.Close();
            //}
            //catch { }
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.Request.Url.ToString() == DummyPageUrl)
            {
                RegisterCacheEntry();
            }

            var app = (HttpApplication)sender;
            if (app.Context.Request.Url.LocalPath.EndsWith("/"))
            {
                app.Context.RewritePath(
                         string.Concat(app.Context.Request.Url.LocalPath, "Default.aspx"));
            }
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs
            string now = DateTime.Now.ToString("yyyy_MM_dd");
            string logFile = System.Web.Hosting.HostingEnvironment.MapPath("~/Logs/Error_" + now + ".log");
            if (!System.IO.File.Exists(logFile))
            {
                System.IO.FileStream fileStream = new System.IO.FileStream(logFile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite);
                Byte[] info = new UTF8Encoding(true).GetBytes("--- LOG DATE: " + DateTime.Now.ToString() + " ---\r\n\r\n");
                fileStream.Write(info, 0, info.Length);
                fileStream.Flush();
                fileStream.Close();
            }
            Logger.Log.LogFileName = logFile;
            Exception ex = Server.GetLastError().GetBaseException();
            Logger.Log.error(ex.ToString());
            // clear errors and redirect page
            //var httpEx = ex as HttpException;
            //HttpContext.Current.ClearError();
            //if (httpEx != null && httpEx.GetHttpCode() == 403)
            //{
            //    Response.Redirect("~/" + Globals.GetUrl("Errors", "Errors.aspx"), true);
            //}
            //else if (httpEx != null && httpEx.GetHttpCode() == 404)
            //{
            //    Response.Redirect("~/" + Globals.GetUrl("Errors", "Errors.aspx"), true);
            //}
            //else
            //{
            //    Response.Redirect("~/" + Globals.GetUrl("ErrorSystem", "ErrorSystem.aspx"), true);
            //}
        }

        protected void Session_End(object sender, EventArgs e)
        {
            Application.Lock();
            Application["UserOnline"] = int.Parse(Application["UserOnline"].ToString()) - 1;
            Application.UnLock();
        }

        protected void Application_End(object sender, EventArgs e)
        {
            Application.Lock();
            Application["UserOnline"] = int.Parse(Application["UserOnline"].ToString()) - 1;
            Application.UnLock();
        }
    }
}